import React, { Component } from 'react';
import { connect } from 'dva';
import _ from 'lodash';
import router from 'umi/router';

import { produce, Draft } from 'immer';
import { Input, Table, Modal, Icon, Upload } from 'antd';
import { Dispatch, AnyAction } from 'redux';
import { Button, Select, Pagination, message, Modal } from 'antd';
import { RouteComponentProps } from 'react-router-dom';
import { isMenuVisible } from '@/utils/utils';
import styles from './index.css';
import BlockList from './BlockList';
import { ConnectState, DeviceCollectionItem, DeviceTypeItem } from '@/models/connect';
import {
  CollectionParamsType,
  deleteDevice,
  downloadExcel,
  exportDevice,
  exportQr,
  importExcel,
} from '@/services/device';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE, RESPONSE_SUCCESS } from '@/const';
import { ColumnProps } from 'antd/lib/table';
import { async } from 'q';
import { getToken } from '@/utils/cookie';

const { confirm } = Modal;

interface DeviceCollectionListProps extends RouteComponentProps<{ deviceTypeNo: string }> {
  deviceCollection: DeviceCollectionItem[];
  deviceTypeNoOptions: DeviceTypeItem[];
  dispatch: Dispatch<AnyAction>;
  deviceCollectionTotal: number;
}

interface DeviceCollectionListState {
  filterQueryParams: CollectionParamsType;
  isTable: boolean;
  showExModel: boolean;
  showModel: false;
  curDevId: string;
  childList: any[];
}

@connect(({ device, statistics }: ConnectState) => ({
  deviceCollection: device.deviceCollection,
  deviceCollectionTotal: device.deviceCollectionTotal,
  deviceTypeNoOptions: device.deviceTypeNoOptions,
  deviceCollectionListData: device.deviceCollectionListData,
  longDeviceType: statistics.longDeviceType,
  childList: device.matchChildsByParents,
  deviceCollection: device.deviceCollection,
}))
class DeviceCollectionList extends Component<DeviceCollectionListProps, DeviceCollectionListState> {
  state: DeviceCollectionListState = {
    filterQueryParams: {
      deviceTypeParentNo: undefined,
      deviceTypeNo: undefined,
      deviceState: '',
      deviceName: '',
      deviceId: '',
      pageNum: DEFAULT_PAGE_NUM,
      pageSize: DEFAULT_PAGE_SIZE,
    },
    isTable: false,
    showModel: false,
    showExModel: false,
    curDevId: '',
  };
  componentDidMount() {
    const { dispatch, match } = this.props;
    dispatch({ type: 'device/clearChildren' });
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceTypeParentNo = this.props.deviceCollectionListData
          ? this.props.deviceCollectionListData
          : undefined;
        draft.filterQueryParams.pageNum = localStorage.getItem('page')
          ? +localStorage.getItem('page')
          : 1;
      }),
      () => {
        this.handleFilterQuery();
      },
    );
    if (this.props.deviceCollectionListData) {
      console.log(this.props.deviceCollectionListData);
      dispatch({
        type: 'device/matchChildsByParents',
        payload: { deviceTypeNo: this.props.deviceCollectionListData },
      });
      this.setState(
        produce((draft: Draft<DeviceCollectionListState>): void => {
          draft.filterQueryParams.deviceTypeParentNo = this.props.deviceCollectionListData
            ? this.props.deviceCollectionListData
            : undefined;
        }),
      );
    }
    dispatch({ type: 'statistics/longDeviceType' });
  }
  componentWillReceiveProps(nextProps: any) {
    const { dispatch } = this.props;
    // dispatch({ type: 'device/clearChildren' });
    if (nextProps.isUpdate !== this.props.isUpdate) {
      this.setState(
        produce((draft: Draft<DeviceCollectionListState>): void => {
          draft.filterQueryParams.pageNum = 1;
        }),
      );
    }
    if (nextProps.deviceCollectionListData !== this.props.deviceCollectionListData) {
      console.log(this.props.deviceCollectionListData);
      if (!this.props.deviceCollectionListData) {
        const { dispatch } = this.props;
        dispatch({ type: 'device/clearChildren' });
      }
      this.setState(
        produce((draft: Draft<DeviceCollectionListState>): void => {
          draft.filterQueryParams.deviceTypeParentNo = nextProps.deviceCollectionListData
            ? nextProps.deviceCollectionListData
            : undefined;
        }),
      );
      const { dispatch } = this.props;
      if (nextProps.deviceCollectionListData) {
        dispatch({
          type: 'device/matchChildsByParents',
          payload: { deviceTypeNo: nextProps.deviceCollectionListData },
        });
      }
      this.setState(
        produce((draft: Draft<DeviceCollectionListState>): void => {
          draft.filterQueryParams.deviceTypeNo = '';
        }),
      );
    }
  }
  // 设备名称
  handleInputDeviceNameChange: React.ChangeEventHandler<HTMLInputElement> = e => {
    e.persist();
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceName = e.target.value;
      }),
    );
  };

  // 设备编号
  handleInputNoChange: React.ChangeEventHandler<HTMLInputElement> = e => {
    const { value } = e.target;
    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
    const isNum = reg.test(value) || value === '';
    if (!isNum) return;
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceId = value;
      }),
    );
  };
  handleChangeCategory = (e: number) => {
    // 资产类别
    console.log(e);
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceTypeParentNo = e;
        draft.filterQueryParams.deviceTypeNo = '';
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
  };
  // 资产种类
  handleSelectDeviceTypeChange = (e: number) => {
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceTypeNo = e;
      }),
    );
  };

  // 设备状态
  handleSelectDeviceStateChange = (e: number) => {
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.deviceState = e;
      }),
    );
  };

  // 搜索
  handleFilterQuery = () => {
    // console.log(this.props.deviceCollectionListData);
    const { dispatch } = this.props;
    dispatch({
      type: 'device/changeDeviceCollectionList',
      payload: this.state.filterQueryParams.deviceTypeParentNo,
    });
    dispatch({ type: 'device/filterDeviceCollection', payload: this.state.filterQueryParams });
  };

  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => this.handleFilterQuery(),
    );
  };

  handleChangeList = () => {
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.isTable = !draft.isTable;
      }),
    );
  };

  handleDelete: (deviceId: string) => void = deviceId => {
    this.setState({ showModel: true, curDevId: deviceId });
  };

  //下载模板
  handleDownloadEx = async () => {
    const res = await downloadExcel();
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(res); // 创建下载的链接
    downloadElement.href = href;
    downloadElement.download = '模板.xls'; // 下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); // 点击下载
    document.body.removeChild(downloadElement); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  };

  // 导出excel
  handleExportEx = async () => {
    if (this.props.deviceCollection.length >= 1) {
      const { match } = this.props;
      const res = await exportDevice({
        deviceId: this.state.filterQueryParams.deviceId
          ? this.state.filterQueryParams.deviceId
          : null,
        deviceName: this.state.filterQueryParams.deviceName,
        deviceState: this.state.filterQueryParams.deviceState,
        deviceTypeParentNo: this.state.filterQueryParams.deviceTypeParentNo,
        deviceTypeNo: this.state.filterQueryParams.deviceTypeNo,
      });
      console.log(res);
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(res); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = '设备.xls'; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    } else {
      message.warning('当前无数据，不能导出');
    }
  };

  // 下载二维码
  handleExportQr = async () => {
    if (this.props.deviceCollection.length >= 1) {
      const { match } = this.props;
      const res = await exportQr({
        deviceId: this.state.filterQueryParams.deviceId
          ? this.state.filterQueryParams.deviceId
          : null,
        deviceName: this.state.filterQueryParams.deviceName,
        deviceState: this.state.filterQueryParams.deviceState,
        deviceTypeParentNo: this.state.filterQueryParams.deviceTypeParentNo,
        deviceTypeNo: this.state.filterQueryParams.deviceTypeNo,
      });
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(res); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = '二维码.zip'; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    } else {
      message.warning('当前无数据，不能导出');
    }
  };

  handleImportEx = async () => {
    this.setState(
      produce((draft: Draft<DeviceCollectionListState>): void => {
        draft.showExModel = true;
      }),
    );
  };

  columns: ColumnProps<DeviceCollectionItem>[] = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
      render: (text, record) => (
        <a
          onClick={() => {
            // isMenuVisible('iot:device:info') &&
            router.push(`/device/detail/${record.deviceTypeNo}/${record.deviceId}`);
          }}
        >
          {record.deviceId}
        </a>
      ),
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产类别',
      dataIndex: 'deviceTypeName',
      key: 'deviceTypeName',
    },
    {
      title: '资产种类',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    {
      title: '显示顺序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '安装位置',
      dataIndex: 'treeTypeName',
      key: 'treeTypeName',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
    },
    {
      title: '厂商唯一编号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
    },
    {
      title: '设备状态',
      dataIndex: 'deviceState',
      key: 'deviceState',
      render: (text, record) => {
        return (
          <span style={{ color: text == '1' ? '#45EBA7' : 'red' }}>
            {text == '1' ? '正常' : '异常'}
          </span>
        );
      },
    },
    {
      title: '状态明细',
      dataIndex: 'stateCodeStr',
      key: 'stateCodeStr',
      render: (text, record) => {
        console.log(record.deviceState);
        return <span style={{ color: record.deviceState == '1' ? '#45EBA7' : 'red' }}>{text}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const { match } = this.props;

        return (
          <span>
            {isMenuVisible('iot:device:update') && (
              <a
                onClick={() => {
                  router.push(`/device/form/${record.deviceTypeParentNo}/${record.deviceId}`);
                  localStorage.setItem('page', this.state.filterQueryParams.pageNum);
                }}
              >
                编辑
              </a>
            )}
            {isMenuVisible('iot:device:delete') && (
              <a onClick={() => this.handleDelete(record.deviceId)}>删除</a>
            )}
            {record.remoteControlField && isMenuVisible('iot:device:remote') && (
              <a
                onClick={() => {
                  // message.info('此设备不支持远程操控!');
                  router.push(`/device/remoteControl`);
                }}
              >
                远程操作
              </a>
            )}
          </span>
        );
      },
    },
  ];

  render() {
    const {
      deviceCollection,
      deviceCollectionTotal,
      deviceTypeNoOptions,
      match,
      longDeviceType = [],
      childList = [],
      deviceCollectionListData,
    } = this.props;
    const { isTable, filterQueryParams } = this.state;
    console.log(deviceCollection);
    const props = {
      name: 'file',
      showUploadList: false,
      action: `${process.env.BASE_UPLOAD_URL}/v1/introduce/importExcel/import`,
      headers: {
        token: getToken(),
      },
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response === RESPONSE_SUCCESS) {
            message.info(`${info.file.name} 导入成功`);
            this.handleFilterQuery();
          } else {
            message.info(info.file.response.msg);
          }
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 导入失败`);
        }
      },
    };
    return isMenuVisible('iot:device:list') && (
      <div className={styles.container}>
        <Modal
          visible={this.state.showExModel}
          title="批量导入"
          centered={true}
          closable={false}
          // onOk={this.handleOk}
          className="modal_box"
          onCancel={() => {
            this.setState({ showExModel: false });
          }}
          footer={null}
        >
          <Upload {...props}>
            <Button>
              <Icon type="upload" /> Click to Upload
            </Button>
          </Upload>
        </Modal>
        <div className={styles.btn}>
          {isMenuVisible('iot:device:add') && (
            <Button
              className="cst-btn-1"
              onClick={() =>
                router.push(
                  `/device/form/${
                    this.props.deviceCollectionListData ? this.props.deviceCollectionListData : ''
                  }`,
                )
              }
            >
              <img src={require('@/assets/images/add.png')} alt="" />
              添加设备
            </Button>
          )}
          {/* <Button className="cst-btn-1" onClick={this.handleImportEx}>
            <img src={require('@/assets/images/import.png')} alt="" />
            批量导入
            
          </Button> */}
          <Upload {...props}>
            {isMenuVisible('iot:device:import') && (
              <Button className="cst-btn-1">
                <img src={require('@/assets/images/import.png')} alt="" />
                批量导入
              </Button>
            )}
          </Upload>
          {isMenuVisible('iot:deviceTemplate:download') && (
            <Button className="cst-btn-1" onClick={this.handleDownloadEx}>
              <img src={require('@/assets/images/download.png')} alt="" />
              下载模板
            </Button>
          )}
          {isMenuVisible('iot:device:export') && (
            <Button className="cst-btn-1" onClick={this.handleExportEx}>
              <img src={require('@/assets/images/add.png')} alt="" />
              导出EXCEL
            </Button>
          )}
          {isMenuVisible('iot:device:exportQrCode') && (
            <Button className="cst-btn-1" onClick={this.handleExportQr}>
              <img src={require('@/assets/images/importcode.png')} alt="" />
              导出二维码
            </Button>
          )}
          {/* <Button
            className="cst-btn-1"
            onClick={this.handleExportQr}
            onClick={() => router.push('/device')}
          >
            <Icon type="rollback" />
          </Button> */}
          <Button
            className="cst-btn-1"
            onClick={this.handleChangeList}
            style={{ position: 'absolute', right: '25px' }}
          >
            {isTable ? (
              <img src={require('@/assets/images/change.png')} alt="" />
            ) : (
              <img src={require('@/assets/images/changeBox.png')} alt="" />
            )}
          </Button>
        </div>
        <div className={styles.filter}>
          <div className={styles.item}>
            <Input
              onChange={this.handleInputNoChange}
              className="itemInput"
              addonBefore="资产编号"
              value={this.state.filterQueryParams.deviceId}
              type="text"
            />
          </div>
          <div className={styles.item}>
            <Input
              onChange={this.handleInputDeviceNameChange}
              value={this.state.filterQueryParams.deviceName}
              className="itemInput"
              addonBefore="设备名称"
              type="text"
            />
          </div>
          <div className={styles.item}>
            <span className={styles.title}>资产类别</span>
            <Select
              placeholder="请选择资产类别"
              value={this.state.filterQueryParams.deviceTypeParentNo}
              allowClear={true}
              style={{ width: 200 }}
              onChange={this.handleChangeCategory}
            >
              {/* <Option value=''>请选择</Option> */}
              {_.map(longDeviceType, (item: any, index: number) => (
                <Select.Option key={index} value={item.deviceTypeNo}>
                  {item.deviceTypeName}
                </Select.Option>
              ))}
            </Select>
          </div>
          <div className={styles.item}>
            <span className={styles.title}>资产种类</span>
            <Select
              allowClear={true}
              placeholder="请先选择资产类别"
              onChange={this.handleSelectDeviceTypeChange}
              value={this.state.filterQueryParams.deviceTypeNo}
              style={{ width: 200 }}
            >
              {_.map(childList, (item: DeviceTypeItem, index: number) => (
                <Select.Option key={index} value={item.deviceTypeNo}>
                  {item.deviceTypeName}
                </Select.Option>
              ))}
            </Select>
          </div>
          <div className={styles.item}>
            <span className={styles.title}>设备状态</span>
            <Select
              allowClear={true}
              onChange={this.handleSelectDeviceStateChange}
              value={this.state.filterQueryParams.deviceState}
              style={{ width: 200 }}
            >
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={2}>异常</Select.Option>
            </Select>
          </div>
          {isMenuVisible('iot:device:list') && (
            <Button
              className="cst-btn-2"
              onClick={() => {
                this.setState(
                  produce((draft: Draft<DeviceCollectionListState>): void => {
                    draft.filterQueryParams.pageNum = 1;
                  }),
                  () => {
                    this.handleFilterQuery();
                  },
                );
              }}
            >
              搜索
            </Button>
          )}
          <Button
            type="link"
            className="cst-btn-2"
            onClick={() => {
              this.setState(
                produce((draft: Draft): void => {
                  draft.filterQueryParams.deviceId = '';
                  draft.filterQueryParams.deviceName = '';
                  draft.filterQueryParams.deviceTypeParentNo = undefined;
                  draft.filterQueryParams.deviceTypeNo = undefined;
                  draft.filterQueryParams.deviceState = undefined;
                }),
                () => {
                  this.handleFilterQuery();
                },
              );
            }}
          >
            重置
          </Button>
        </div>
        <div className={styles.imgcontent}>
          {!isTable ? (
            deviceCollection.length ? (
              <div className={styles.diviceName}>
                {_.map(deviceCollection, (item, index) => (
                  <BlockList
                    handleEdite={() =>
                      router.push(`/device/form/${item.deviceTypeParentNo}/${item.deviceId}`)
                    }
                    handleDelete={this.handleDelete}
                    key={index}
                    deviceListPage={this.state.filterQueryParams.pageNum}
                    item={item}
                  />
                ))}
              </div>
            ) : (
              <div className={styles.noData}>
                <div>
                  <img src={require('@/assets/nodata.png')} alt="" />
                </div>
                <p>暂无数据或无设备权限</p>
              </div>
            )
          ) : (
            <Table
              scroll={{ y: '500px' }}
              pagination={false}
              columns={this.columns}
              dataSource={deviceCollection}
            />
          )}
        </div>
        <div className={styles.pagination}>
          <Pagination
            onChange={this.handlePageChange}
            defaultCurrent={this.state.filterQueryParams.pageNum}
            current={this.state.filterQueryParams.pageNum}
            defaultPageSize={DEFAULT_PAGE_SIZE}
            total={deviceCollectionTotal}
          />
          <span className={styles['pagination-title']}>
            第{this.state.filterQueryParams.pageNum}页 共
            {deviceCollectionTotal ? deviceCollectionTotal : '0'}条
          </span>
        </div>
        <Modal
          visible={this.state.showModel}
          title="提示"
          centered={true}
          closable={false}
          // onOk={this.handleOk}
          className="modal_box"
          onCancel={() => {
            this.setState({ showModel: false });
          }}
          footer={null}
        >
          <div className={styles.tcTop_box}>
            <div className={styles.tc_left} />
            <div className={styles.tc_right}>
              <Icon
                className="tc_right_close"
                type="close"
                onClick={() => {
                  this.setState({ showModel: false });
                }}
              />
            </div>
            <div className={styles.tip_area}>确认删除?</div>
            <div className={styles.footBtnArea}>
              <div
                className={styles.foot_btn}
                style={{ marginRight: '30px' }}
                onClick={() => {
                  this.setState({ showModel: false });
                }}
              >
                取消
              </div>
              <div
                className={styles.foot_btn}
                onClick={async () => {
                  const [err, data] = await deleteDevice({ deviceId: this.state.curDevId });
                  if (!err) {
                    message.success('删除成功');
                    this.handleFilterQuery();
                    this.setState({ showModel: false });
                  }
                }}
              >
                确认
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default DeviceCollectionList;
